import { getUserInfo } from '@/api/user'
import { deleteRedisUsers, getMenu, login, loginByMobile, logout } from '@/api/login'
import { orderBy } from 'lodash-es'
import store from '@/store'
import { addRouteFromMenu, resetRouter } from '@/router'
import { encryption } from '@/util'
import { cimPushManager } from '@/util/web-socket'
import { excludeTreeNode, transformTree } from '@web-utils/core'
import { deepClone } from '@web-utils/integrations/lodash'
import { isURL } from '@/util/validate'
import { iframePath, isFormPath, isNewTabPath, urlToHash } from '@/util/iframe'

export default {
  async handleLogin({ commit, dispatch }, { username, password, code, auto, grantType, randomStr, validCode }) {
    // 登录
    try {
      let res
      if (grantType === 'mobile') {
        res = await loginByMobile({ code, mobile: 'code', grantType })
      } else {
        username = username.trim()

        const userInfo = { username, password, code: validCode, randomStr }
        let user = {}
        user = encryption({ data: userInfo, key: 'pigxpigxpigxpigx', param: ['password'] })
        res = await login({
          username: user.username,
          password: user.password,
          grantType,
          randomStr: user.randomStr,
          validCode: user.code
        })
      }

      if (res && res.data.access_token) {
        commit('reset')
        const token = res.data.access_token
        commit('setToken', { token, auto })
        commit('validToken')
        await dispatch('getUserInfo')
        return Promise.resolve(res)
      }
      return Promise.reject(res)
    } catch (e) {
      return Promise.reject(e)
    }
  },
  async handleLogout({ commit, state }) {
    try {
      if (state.tokenValid) {
        await deleteRedisUsers()
        await logout()
        cimPushManager.stop()
      }
      commit('invalidToken')
      commit('reset')
      return Promise.resolve({ message: 'success' })
    } catch (e) {
      return Promise.reject(e)
    }
  },
  async getUserInfo({ dispatch, commit, getters }) {
    try {
      const res = await getUserInfo()

      const { code, data } = res.data
      if (code === 0) {
        const { sysUser, permissions, roles, infos } = data

        const permissionMap = {}
        for (let i = 0; i < permissions.length; i++) {
          permissionMap[permissions[i]] = true
        }

        commit('notEmpty')
        commit('validToken')
        const patch = {
          sysUser,
          permissions: permissionMap,
          roles,
          userInfoDetail: infos
        }

        commit('patch', patch)
        cimPushManager.setAccount(sysUser.userId)
        await dispatch('getMenu')

        if (getters.isTempUser) {
          store.commit('viewState/setTabs', [])
        }

        await store.dispatch('im/getUnreadMessageCount')
        await store.dispatch('message/fetchMessage')

        return Promise.resolve(res)
      }
      return Promise.reject(res)
    } catch (e) {
      return Promise.reject(e)
    }
  },
  async getMenu({ commit }) {
    const res = await getMenu()
    const data = orderBy(res.data.data, value => Number(value.sortOrder))

    const menuProps = {
      label: 'label',
      path: 'path',
      icon: 'icon',
      children: 'children'
    }

    const menus = transformTree(deepClone(data), node => {
      if (isURL(node[menuProps.path]) && !isNewTabPath(node.path)) {
        const hash = urlToHash(node[menuProps.path])
        node[menuProps.path] = `/${iframePath}/${hash}`
      }
      return node
    })

    // 过滤掉表单菜单和无效菜单
    const patch = { menu: excludeTreeNode(menus, node => (node.children?.length || node.path) && !isFormPath(node.path)) }
    // 添加左侧菜单
    commit('patch', patch)

    // 添加路由
    await resetRouter()
    addRouteFromMenu(data)
  }
}
